﻿using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataSave;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using LdtJudge.DataEngine.Common.XmlUtility;

namespace LdtJudge.DataEngine.Common.DataSave
{
    public class DataSaveOrder
    {
        public DataContext dataContext;

        public XmlDocument OrderModel(XmlDocument xmlTemplate, ReorderModel reorderModel, List<DataModel> ModelList)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            XmlDocument xmlDocument = new XmlDocument();
            if (xmlTemplate != null && !string.IsNullOrEmpty(xmlTemplate.OuterXml))
            {
                List<DataModel> dataModelList = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(ModelList));
                CaseTypeModel caseTypeModel = new CaseTypeModel();
                if (reorderModel != null)
                {
                    caseTypeModel = reorderModel.caseTypeModelList.FirstOrDefault(a => a.code.ToLower() == dataContext.DataLayerAns.CaseType.ToLower());
                }
                List<string> pathList = new List<string>();
                XmlNodeList xmlNodeList = xmlTemplate.SelectNodes("/*");
                XmlPathConver(xmlNodeList, "", pathList);
                List<DataModel> dataModels = new List<DataModel>();
                foreach (string path in pathList)
                {
                    List<DataModel> modelList = dataModelList.Where(a => a.XmlPath == path).ToList();
                    OrderNodeModel orderNodeModel = new OrderNodeModel();
                    if (caseTypeModel != null)
                    {
                        orderNodeModel = caseTypeModel.orderNodeModelList.FirstOrDefault(a => a.xmlpath == path);
                    }
                    if (modelList != null)
                    {
                        if (modelList.Count > 0)
                        {
                            if (modelList.Count == 1)
                            {
                                dataModels.Add(modelList[0]);
                                dataModelList.Remove(modelList[0]);
                            }
                            else
                            {
                                if (orderNodeModel != null)
                                {
                                    #region 排序配置进行
                                    //存在排序配置
                                    if (orderNodeModel.conditionModelList != null)
                                    {
                                        ConditionModel conditionModel = orderNodeModel.conditionModelList[0];
                                        if (!string.IsNullOrEmpty(conditionModel.order))
                                        {
                                            if (conditionModel.order == "1")
                                            {
                                                if (conditionModel.type == "int")
                                                {
                                                    modelList = modelList.OrderBy(a => int.Parse(a.AttributesList.FirstOrDefault(b => b.Name == conditionModel.elementname).sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue)).ToList();
                                                }
                                                else
                                                {
                                                    modelList = modelList.OrderBy(a => a.AttributesList.FirstOrDefault(b => b.Name == conditionModel.elementname).sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue).ToList();
                                                }

                                            }
                                            else
                                            {
                                                if (conditionModel.type == "int")
                                                {
                                                    modelList = modelList.OrderByDescending(a => int.Parse(a.AttributesList.FirstOrDefault(b => b.Name == conditionModel.elementname).sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue)).ToList();
                                                }
                                                else
                                                {
                                                    modelList = modelList.OrderByDescending(a => a.AttributesList.FirstOrDefault(b => b.Name == conditionModel.elementname).sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue).ToList();
                                                }

                                            }
                                            foreach (DataModel model in modelList)
                                            {
                                                dataModels.Add(model);
                                                dataModelList.Remove(model);
                                            }
                                        }
                                        else
                                        {
                                            modelList = OrderDataModel(conditionModel, modelList);
                                            foreach (DataModel model in modelList)
                                            {
                                                dataModels.Add(model);
                                                dataModelList.Remove(model);
                                            }
                                        }

                                    }
                                    #endregion
                                }
                                else
                                {
                                    //没有排序配置
                                    foreach (DataModel model in modelList)
                                    {
                                        dataModels.Add(model);
                                        dataModelList.Remove(model);
                                    }
                                }

                            }
                        }
                    }
                }

                if (dataModelList.Count > 0)
                {
                    dataModels.AddRange(dataModelList);
                }
                dataModelList = dataModels;
                if (dataModelList.Count > 0)
                {
                    xmlDocument = xmlUtilCommon.DataModelByXml(dataModelList, "");
                }
            }

            return xmlDocument;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="conditionModel"></param>
        /// <param name="dataModelList"></param>
        public List<DataModel> OrderDataModel(ConditionModel conditionModel, List<DataModel> dataModelList)
        {
            if (conditionModel.valelistModelList != null && conditionModel.valelistModelList.Count > 0)
            {
                List<DataModel> modelList = new List<DataModel>();
                foreach (var valelistModel in conditionModel.valelistModelList)
                {
                    if (dataModelList.FirstOrDefault(a => a.AttributesList.FirstOrDefault(a => a.Name == conditionModel.elementname) != null) != null)
                    {
                        var model = dataModelList.Where(x => x.AttributesList.Any(s => s.Name == conditionModel.elementname))
                                                 .Where(x => x.AttributesList.FirstOrDefault(s => s.Name == conditionModel.elementname).sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == valelistModel.value)
                                                 .FirstOrDefault();
                        if (model != null)
                        {
                            List<DataModel> dataList = dataModelList.Where(x => x.AttributesList.Any(s => s.Name == conditionModel.elementname))
                                                                    .Where(a => a.AttributesList.FirstOrDefault(b => b.Name == conditionModel.elementname).sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == valelistModel.value)
                                                                    .ToList();

                            if (conditionModel.conditionModelList != null && conditionModel.conditionModelList.Count > 0)
                            {
                                dataList = OrderDataModel(conditionModel.conditionModelList[0], dataList);
                            }
                            foreach (var datamodel in dataList)
                            {
                                modelList.Add(datamodel);
                                dataModelList.Remove(datamodel);
                            }
                        }
                    }

                }
                modelList.AddRange(dataModelList);
                dataModelList = modelList;
            }
            return dataModelList;
        }

        /// <summary>
        /// 将xml模块转换为xpath集合
        /// </summary>
        /// <param name="nodeList">节点</param>
        /// <param name="parentPath"></param>
        /// <param name="pathList"></param>
        public void XmlPathConver(XmlNodeList nodeList, string parentPath, List<string> pathList)
        {
            foreach (XmlNode node in nodeList)
            {
                string xmlpath = "";
                if (string.IsNullOrEmpty(parentPath))
                {
                    xmlpath = node.Name;
                }
                else
                {
                    xmlpath = parentPath + @"/" + node.Name;
                }

                pathList.Add(xmlpath);
                XmlPathConver(node.ChildNodes, xmlpath, pathList);
            }
        }

        /// <summary>
        /// 证据内容详情节点数据排序
        /// </summary>
        /// <param name="dataModelList">优选结果对象</param>
        /// <returns></returns>
        public void OrderEvidDataModel(List<DataModel> dataModelList)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            if (dataContext.DataLayerAns.OredContents != null && dataContext.DataLayerAns.OredContents.Any() && dataContext.DataLayerAns.EvidSortedState != 1)
            {
                var orderSfids = dataContext.DataLayerAns.OredContents.Select(x => x.sfid).ToList();
                //获取阶段数据
                var dataModels = xmlUtilCommon.SubordinateDataModelList(dataModelList, dataContext.DataLayerOpt.StageProcessResultModel.dataModel);
                //获取证据详情节点数据
                var evidDetails = dataModels.Where(x => x.XmlPath.EndsWith("详情") && x.XmlPath.Contains("证据") && !x.XmlPath.Contains("证据内容") && x.AttributesList.Any(a => a.Name == "来源姓名")).ToList();
                if (evidDetails != null && evidDetails.Any())
                {
                    foreach (var evidItem in evidDetails)
                    {
                        //获取证据详情下的所有子节点数据
                        var subDatas = xmlUtilCommon.SubordinateDataModelList(dataModels, evidItem);
                        //从子节点中获取证据内容详情节点数据
                        var contentDetails = subDatas.Where(x => x.XmlPath.EndsWith("详情") && x.XmlPath.Contains("证据内容") && !x.XmlPath.Contains("证据要素")).ToList();
                        if (contentDetails != null && contentDetails.Any())
                        {
                            //获取证据内容详情节点数据中的sfid
                            var contentSfids = contentDetails.Where(x => x.AttributesList.Any(a => a.Name == "证据文件ID"))
                                .Where(x => !string.IsNullOrWhiteSpace(x.AttributesList.FirstOrDefault(a => a.Name == "证据文件ID").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue))
                                .Select(x => x.AttributesList.FirstOrDefault(a => a.Name == "证据文件ID").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue).ToList();
                            var dealDetail = contentDetails.Select(x => x.Clone()).ToList();
                            //去除原先数据集合中的证据内容详情节点
                            foreach (var delItem in contentDetails)
                            {
                                dataModelList.Remove(delItem);
                            }
                            if (contentSfids != null && contentSfids.Any())
                            {
                                //取需要排序的sfid集合
                                var orderevids = orderSfids.Intersect(contentSfids).ToList();
                                if (orderevids != null && orderevids.Any())
                                {
                                    //var messagesourmodel = XmlUtility.XmlUtility.DataModelByXml(dealDetail);
                                    var orderConfig = dataContext.DataLayerAns.OredContents.Where(x => orderevids.Contains(x.sfid))
                                                                 .OrderBy(x => x.OrderNumber).ToList();
                                    foreach (var orderItem in orderConfig)
                                    {
                                        //var addData = dealDetail.Where(x => x.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SourceFLID == orderItem.sfid).FirstOrDefault();
                                        var addData = dealDetail.Where(x => x.AttributesList.FirstOrDefault(a => a.Name == "证据文件ID")?.sourceList.FirstOrDefault(c => c.IsCheck == "1")?.SaveValue == orderItem.sfid).FirstOrDefault();
                                        if (addData != null)
                                        {
                                            var xh = addData.AttributesList.FirstOrDefault(x => x.Name == "证据序号");
                                            if (xh == null)
                                                addData.AttributesList.Add(new AttributeInfo() { Name = "证据序号", sourceList = new List<Source>() { new Source() { SaveValue = orderItem.OrderNumber.ToString(), IsCheck="1" } } });
                                            dataModelList.Add(addData);
                                            dealDetail.Remove(addData);
                                        }
                                    }
                                    

                                    dataContext.DataLayerAns.EvidSortedState = 1;
                                   
                                }
                                if (dealDetail != null && dealDetail.Any())
                                {
                                    foreach (var unOrderItem in dealDetail)
                                    {
                                        dataModelList.Add(unOrderItem);
                                    }
                                    dealDetail.Clear();
                                }
                            }
                        }
                    }
                }
            }
        }

    }
}
